#pragma once


class CParser
{
public:
	CParser( const BYTE* pBuffer, int nLen )
		: m_pBuffer( pBuffer )
		, m_nBufLen( nLen )
		, m_nRover( 0 )
	{
		ASSERT( m_pBuffer != NULL );
		ASSERT( m_nBufLen > 0 );
	}

	const BYTE* NextPack( int& nLen );

	void Reset( void );

private:
	int Search( BYTE b, int nPos );

private:
	const BYTE* m_pBuffer;
	const int	m_nBufLen;

	int	m_nRover;
};

inline const BYTE* CParser::NextPack( int& nLen )
{
	const BYTE HEAD = 0xFF;
	const BYTE TAIL = 0x00;

	if( m_nRover >= m_nBufLen )
	{
		return NULL;
	}

	if( m_pBuffer[m_nRover] != HEAD )
	{
		return NULL;
	}

	int nTail = Search( TAIL, m_nRover );
	if( nTail < 0 )
	{
		return NULL;
	}

	ASSERT( nTail > m_nRover );
	ASSERT( nTail < m_nBufLen );

	nLen = nTail - m_nRover + 1;
	
	const BYTE* pRet = m_pBuffer + m_nRover;
	m_nRover += nLen;

	return pRet;
}

inline void CParser::Reset( void )
{
	m_nRover = 0;
}

inline int CParser::Search( BYTE b, int nPos )
{
	ASSERT( nPos >=0 );
	ASSERT( nPos < m_nBufLen );

	for( int i=nPos; i<m_nBufLen; ++i )
	{
		if( b == m_pBuffer[i] )
		{
			return i;
		}
	}

	return -1;
}